package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/go-errors/errors"
)

func ParseBody(body []byte, obj interface{}) error {
	return json.Unmarshal(body, obj)
}

func Validate(obj interface{}) error {
	valid := validation.Validation{}
	b, err := valid.Valid(obj)
	if err != nil {
		return err
	}
	if !b {
		var buffer bytes.Buffer
		for _, err := range valid.Errors {
			buffer.WriteString(fmt.Sprintf("%s:%s", err.Key, err.Value))
		}
		return errors.New(buffer.String())
	}
	return nil
}

func ParseBodyAndValidate(body []byte, obj interface{}) error {
	if err := json.Unmarshal(body, obj); err != nil {
		return err
	}
	return Validate(obj)
}
